package com.tankbattle.stage.body.map;

import com.tankbattle.stage.body.buildings.*;
import com.tankbattle.stage.body.tank.Tank;

import java.util.List;
import java.util.Random;

/**
 * @author 13797
 */
public class StageRandom extends Map {

    private static final int MAP_WIDTH = 560;
    private static final int MAP_HEIGHT = 560;
    private static final int BLOCK_SIZE = 32;
    // 出生点和基地的安全区域半径
    private static int SAFE_ZONE_RADIUS = 5 * BLOCK_SIZE;
    /**
     * 排除顶行
     */
    private static int topExcludeRows = 1;
    /**
     * 排除底行
     */
    private static int bottomExcludeRows = 3;
    private final Random random = new Random();

    public StageRandom() {
        // 初始化地图状态数组，false表示未被占用，true表示已被占用
        boolean[][] mapStatus = new boolean[MAP_WIDTH / BLOCK_SIZE][MAP_HEIGHT / BLOCK_SIZE];

        Tank.tanks = new int[MAP_WIDTH][MAP_HEIGHT];
        walls.add(new Wall(260 - 16 - 32, 520 - 32));
        walls.add(new Wall(260 - 16 - 32, 520 - 32 * 2));
        walls.add(new Wall(260 - 16, 520 - 32 * 2));
        walls.add(new Wall(260 + 16, 520 - 32));
        walls.add(new Wall(260 + 16, 520 - 32 * 2));
        steels.add(new Steel(260 - 16, 520 - 46 * 4));

        // 初始化出生点和基地（必须保留的关键区域）
        initHomeLocation();
        // 随机添加墙
        addRandomObjects(mapStatus, walls, Wall.class, 40);
        initWallLocation();
        // 随机添加草；没有碰撞体积 只是贴图
        addRandomObjects(mapStatus, grasses, Grass.class, 20);
        // 随机添加水
        addRandomObjects(mapStatus, seas, Sea.class, 10);
        initSeaLocation();
        //添加随机铁
        addRandomObjects(mapStatus, steels, Steel.class, 20);
        initSteelLocation();

        //没有碰撞体积只是贴图；
        addRandomObjects(mapStatus, ices, Ice.class, 10);

    }

    private <T> void addRandomObjects(boolean[][] mapStatus, List<T> objectList, Class<T> objectClass, int numObjects) {
        // 计算有效Y轴范围
        int maxY = (MAP_HEIGHT / BLOCK_SIZE) - bottomExcludeRows;

        for (int i = 0; i < numObjects; i++) {
            int x, y;
            int attempts = 0;
            do {
                x = random.nextInt(MAP_WIDTH / BLOCK_SIZE) * BLOCK_SIZE;
                y = (random.nextInt(maxY - topExcludeRows) + topExcludeRows) * BLOCK_SIZE;
                attempts++;

                // 防止死循环
                if (attempts > 100) {
                    break;
                }
            } while (mapStatus[x / BLOCK_SIZE][y / BLOCK_SIZE]);

            if (attempts <= 100) {
                try {
                    T object = objectClass.getConstructor(int.class, int.class).newInstance(x, y);
                    objectList.add(object);
                    mapStatus[x / BLOCK_SIZE][y / BLOCK_SIZE] = true;
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
    }
}
